<template>
    <div>
        <basic-layout title="餐饮订单" :isDefaultHeader="true" :showAddBtn="false">
            <template #defaultHeader>
                <van-row class="search-row" style="background: #4eb3e9;">
                    <van-search v-model="queryFormData.keyword" shape="round" maxlength="20" background="transparent" placeholder="订单编号 / 菜肴名称" @search="onRefresh" />
                    <van-icon name="filter-o" @click="$refs.queryPopupRef.show = true" />
                </van-row>
            </template>
            <div class="columnFlex">
                <!-- 列表 -->
                <van-row class="listCon">
                    <van-tabs v-model="curTabName" @click="onRefresh">
                        <van-tab v-for="item in tabsList" :name="item.name" :title="item.title" :key="item.title"></van-tab>
                    </van-tabs>
                    <van-list class="orderList" v-model="listLoading" :finished="finished" :finished-text="orderList.length ? '没有更多了' : ''" @load="onLoad">
                        <div v-for="(item, index) in orderList" :key="item.cookbookId" class="list-item">
                            <div class="head flexRow">
                                <div class="left">
                                    <b>{{item.canteenName}}</b>
                                    <span>( {{item.cookbookDate}} )</span>
                                </div>
                                <div class="right">
                                    <span class="status" :class="'status' + item.orderStatus">{{curTabName === '6' ? item.afterSalesStatusName : item.orderStatusName}}</span>
                                </div>
                            </div>
                            <div class="middle">
                                <div>
                                    <p class="tip">共 {{item.listDetail.length}} 件</p>
                                    <dl v-for="val in item.listDetail" :key="val.dishId">
                                        <dt>
                                            <img :src="fileUrlObj[val.fileCode] || (loading ? 'images/loading.gif' : 'images/noImgData.png')">
                                            <p>{{val.dishName}}</p>
                                        </dt>
                                        <dd>
                                            <span class="money">￥{{val.buyPrice}}</span>
                                            <p class="buyAmount">x {{val.buyAmount}}</p>
                                        </dd>
                                    </dl>
                                </div>
                            </div>
                            <div class="orderInfo flexRow">
                                <div class="left">
                                    订单编号：<span>{{item.orderNo}}</span>
                                </div>
                                <div class="right">
                                    <span>{{item.mealsTypeName}}</span>
                                </div>
                            </div>
                            <div class="orderInfo flexRow">
                                <div class="left">
                                    订单时间：<span>{{item.createTime}}</span>
                                </div>
                                <div class="right">
                                    <span>{{item.payMethodName}}</span>
                                </div>
                            </div>
                            <div class="bottom flexRow">
                                <div class="left">
                                    总价：<span class="money">￥{{item.amount}}</span>
                                </div>
                                <div class="right">
                                    <a v-if="item.orderStatus === '1' && item.payMethod === '2' && !item.defaultHide" @click="handlePayment(item)">支付</a>
                                    <a v-if="item.orderStatus === '3'" @click="handleReceipt(item)">确认收货</a>
                                    <a v-if="item.orderStatus === '4' && item.commentStatus === '2'" @click="handleEvaluate(item)">评价</a>
                                    <a v-if="(item.orderStatus === '1' && !item.defaultHide) || item.orderStatus === '2'" @click="handleCancel(item)">取消</a>
                                    <a v-if="item.orderStatus === '4' && item.payMethod === '2' && item.afterSalesStatus === '1'" @click="handleUpdRefund(item)">申请退款</a>
                                    <a v-if="curTabName === '6' && (item.afterSalesStatus === '3' || item.afterSalesStatus === '4')" @click="handleDelete(item)">删除</a>
                                </div>
                            </div>
                            <div class="surplusTime" v-if="item.orderStatus === '1'">
                                <span>{{ item.payMethod === '1' ? '线下确认剩余时间' : '支付剩余时间' }}：</span>
                                <van-count-down :time="item.surplusTime" format="HH 时 mm 分 ss 秒" @finish="handleFinish(item, index)" />
                            </div>
                        </div>
                        <van-empty v-if="!listLoading && !orderList.length" class="custom-image" :image="require('../../../../assets/images/empty.png')" description="暂无数据" />
                    </van-list>
                </van-row>
            </div>
        </basic-layout>
        <full-loading v-if="spinLoading"></full-loading>
        <!-- 筛选条件弹出框 -->
        <queryPopup ref="queryPopupRef" @handleSearch="onRefresh" @handleReset="handleReset">
            <van-form class="filterBox">
                <label>订单餐次</label>
                <van-field>
                    <template #input>
                        <div class="textCon" @click="showPicker = true">
                            <span v-if="!queryFormData.mealsTypeName" style="color: #aaa">请选择订单餐次</span>
                            <span v-else>{{ queryFormData.mealsTypeName }}</span>
                        </div>
                    </template>
                    <template #button>
                        <van-icon v-if="queryFormData.mealsTypeName" name="cross" @click="clearPicker('type')" />
                    </template>
                </van-field>
                <label>订单日期</label>
                <van-field>
                    <template #input>
                        <div class="textCon" @click="showTimePicker = true">
                            <span v-if="!queryFormData.orderStartTime" style="color: #aaa">请选择订单日期</span>
                            <span v-else>{{ queryFormData.orderStartTime }} ~ {{queryFormData.orderEndTime}}</span>
                        </div>
                    </template>
                    <template #button>
                        <van-icon v-if="queryFormData.orderStartTime" name="cross" @click="clearPicker('date')" />
                    </template>
                </van-field>
            </van-form>
        </queryPopup>
        <!-- 餐次列表选择 -->
        <van-action-sheet v-model="showPicker" cancel-text="取消" :actions="mealsTypeList" @select="onConfirm" />
        <!-- 订单日期 -->
        <van-calendar v-model="showTimePicker" :min-date="minDate" :max-date="maxDate" :allow-same-day="true" type="range" @confirm="onTimeConfirm" />
        <!-- 评价 -->
        <fullscreenModal :modal="showEvaluateModal" label="评价订单" :isShowEdit="false" editType="other" @handleClose="showEvaluateModal = false" @handleSave="$refs.evaluateRef.handleSave()">
            <evaluate @close="showEvaluateModal=false" @refresh="onRefresh()" ref="evaluateRef" />
        </fullscreenModal>
        <!-- 取消订单 -->
        <fullscreenModal :modal="showCancelModal" label="取消订单" :isShowEdit="false" editType="other" @handleClose="showCancelModal = false" @handleSave="handleSure()">
            <van-form ref="cancelForm">
                <van-field v-model="cancelFormData.retreatReason" style="border-bottom: 1px solid #eee;" required rows="5" name="取消原因" label="取消原因" type="textarea" maxlength="128" placeholder="请输入取消原因" show-word-limit :rules=rules.retreatReason />
            </van-form>
        </fullscreenModal>
        <!-- 退款 -->
        <fullscreenModal :modal="showUpdRefundModal" label="退款" :isShowEdit="false" editType="other" @handleClose="showUpdRefundModal = false" @handleSave="$refs.refundFormRef.handleUpdRefundSure()">
            <refundForm @close="showUpdRefundModal=false" @refresh="onRefresh()" ref="refundFormRef" />
        </fullscreenModal>
        <!-- 支付弹出层 -->
        <confirmOrder ref="payment" @paySuccess="paySuccess" :money="payMoney" />
    </div>
</template>

<script>
    import evaluate from './evaluate';
    import refundForm from './refundForm';
    import confirmOrder from '@/components/confirmOrder';
    import { queryFileList, queryDic } from '@/api/common';
    import { getOrderInfoByPageForUser, updateCancelOrder, updateReceiptOrder, delOrderBack } from '@/api/srvAssurance/smarcatering/myOrder';
    import { payment } from '@/api/srvAssurance/smarcatering/takeawayOrder';
    import { queryPersonPayment } from '@/api/platframe/mainFrame/pay';
    
    export default {
        name: 'myOrder',
        components: {
            evaluate,
            refundForm,
            confirmOrder
        },
        data () {
            return {
                loading: false,
                listLoading: false,
                spinLoading: false,
                finished: false,
                showPicker: false,
                showTimePicker: false,
                showEvaluateModal: false,
                showCancelModal: false,
                showUpdRefundModal: false,
                minDate: new Date(new Date().getFullYear() - 1, 0, 1),
                maxDate: new Date(),
                queryFormData: {
                    keyword: '',
                    orderStartTime: '',
                    orderEndTime: '',
                    mealsType: '',
                    mealsTypeName: ''
                },
                tabsList: [
                    { name: '0', title: '全部订单' },
                    { name: '1', title: '待付款' },
                    { name: '2', title: '待发货' },
                    { name: '3', title: '待收货' },
                    { name: '4', title: '交易成功' },
                    { name: '5', title: '交易关闭' },
                    { name: '6', title: '退款' },
                ],
                curTabName: '0',
                currentPage: 1,
                orderList: [],
                fileUrlObj: {},
                cancelFormData: {
                    orderId: '',
                    orderStatus: '',
                    retreatReason: ''
                },
                rules: {
                    retreatReason: [
                        { required: true, message: '请输入取消原因', trigger: 'blur' },
                        { pattern: this.$commonReg.textAreaReg, message: this.$commonReg.textAreaMsg, trigger: 'blur' }
                    ]
                },
                mealsTypeList: [],
                payMoney: '',
                payOrderId: ''
            }
        },
        mounted () {
            this.getOrderList();
            this.queryDicData();
        },
        methods: {
            // 查询订单列表
            getOrderList () {
                if (this.queryFormData.keyword && !this.$commonReg.textReg.test(this.queryFormData.keyword)) {
                    this.$Notify({ type: 'warning', message: `关键字${this.$commonReg.textMsg}` });
                    return;
                }
                let params = {
                    keyword: this.queryFormData.keyword || '',
                    orderStartTime: this.queryFormData.orderStartTime || '',
                    orderEndTime: this.queryFormData.orderEndTime || '',
                    mealsType: this.queryFormData.mealsType || '',
                    orderStatus: this.curTabName === '0' ? '' : this.curTabName,
                    pageNum: this.currentPage,
                    pageSize: 10
                }
                this.listLoading = true;
                let fileCodeArr = [];
                getOrderInfoByPageForUser(params).then(res => {
                    this.listLoading = false;
                    if (res.code === 1000 && res.data) {
                        res.data.records.forEach(item => {
                            item.defaultHide = false;
                            if (item.expirationTime) {
                                item.surplusTime = new Date(item.expirationTime).getTime() - Date.now();
                            } else {
                                item.surplusTime = -1;
                            }
                            item.listDetail.forEach(val => {
                                if (val.fileCode && !this.fileUrlObj[val.fileCode]) {
                                    fileCodeArr.push(val.fileCode);
                                    this.fileUrlObj[val.fileCode] = '';
                                }
                            })
                        })
                        this.orderList = [...this.orderList, ...res.data.records];
                        if (fileCodeArr.length) {
                            this.queryFileInfoData(fileCodeArr);
                        }
                        if (this.orderList.length >= res.data.total) {
                            this.finished = true;
                        }
                    } else {
                        this.finished = true;
                    }
                }).catch(() => {
                    this.listLoading = false;
                    this.finished = true;
                })
            },
            onRefresh () {
                this.finished = false;
                this.orderList = [];
                this.currentPage = 1;
                this.getOrderList();
            },
            onLoad () {
                this.currentPage++;
                this.getOrderList();
            },
            // 支付倒计时结束
            handleFinish (item) {
                if (item.orderStatus === '1' && item.payMethod === '2') {
                    item.defaultHide = true;
                }
            },
            // 餐次列表选择
            onConfirm (item) {
                this.queryFormData.mealsType = item.value;
                this.queryFormData.mealsTypeName = item.name;
                this.showPicker = false;
                this.onRefresh();
            },
            // 订单日期选择
            onTimeConfirm (date) {
                const [start, end] = date;
                this.queryFormData.orderStartTime = new Date(start).format('yyyy-MM-dd');
                this.queryFormData.orderEndTime = new Date(end).format('yyyy-MM-dd');
                this.showTimePicker = false;
                this.onRefresh();
            },
            // 清空查询条件
            clearPicker (type) {
                if (type === 'type') {
                    this.queryFormData.mealsType = '';
                    this.queryFormData.mealsTypeName = '';
                } else if (type === 'date') {
                    this.queryFormData.orderStartTime = '';
                    this.queryFormData.orderEndTime = '';
                }
                this.onRefresh();
            },
            // 重置
            handleReset () {
                this.queryFormData = {
                    keyword: '',
                    orderStartTime: '',
                    orderEndTime: '',
                    mealsType: '',
                    mealsTypeName: ''
                };
                this.onRefresh();
            },
            // 支付
            handlePayment (item) {
                this.payOrderId = item.orderId;
                this.payMoney = item.amount + '';
                this.$refs.payment.isProof();
                // let staffId = sessionStorage.getItem("userid");
                // this.spinLoading = true;
                // queryPersonPayment({ staffId }).then(res => {
                //     if (res.code === 1000 && res.data) {
                //         if (res.data.payment_free === "1") { // 免密支付
                //             this.paySuccess();
                //         } else { // 密码校验
                //             this.spinLoading = false;
                //             this.payMoney = item.amount + '';
                //             this.$refs.payment.showModel = true;
                //         }
                //     } else {
                //         this.spinLoading = false;
                //     }
                // }).catch(() => {
                //     this.spinLoading = false;
                // })
            },
            // 支付成功
            paySuccess () {
                this.spinLoading = true;
                payment([this.payOrderId]).then(_res => {
                    this.spinLoading = false;
                    if (_res.code === 1000 && _res.data) {
                        if (_res.data.code === '1') { // 支付成功
                            this.$Notify({ type: 'success', message: '支付成功！' });
                            this.onRefresh();
                        } else {
                            let msg = '';
                            if (_res.data.data && _res.data.data.payFailList && _res.data.data.payFailList.length) {
                                msg = _res.data.data.payFailList[0].msg || '';
                            }
                            this.$Notify({ type: 'warning', message: `支付失败！${msg ? ('失败原因：' + msg) : ''}` });
                        }
                    }
                }).catch(() => {
                    this.spinLoading = false;
                })
            },
            // 确认收货
            handleReceipt (item) {
                this.$Dialog
                    .confirm({
                        title: "是否确定确认收货？",
                    })
                    .then(() => {
                        this.spinLoading = true;
                        updateReceiptOrder(item.orderId).then(res => {
                            this.spinLoading = false;
                            if (res.code === 1000) {
                                this.$Notify({ type: 'success', message: '确认收货成功！' });
                                this.onRefresh();
                            }
                        }).catch(() => {
                            this.spinLoading = false;
                        })
                    })
                    .catch(() => { });
            },
            // 评价
            handleEvaluate (item) {
                this.showEvaluateModal = true;
                this.$refs.evaluateRef.resetForm();
                this.$refs.evaluateRef.getData(item);
            },
            // 取消订单
            handleCancel (item) {
                this.$Dialog
                    .confirm({
                        title: "是否确定取消该订单？",
                    })
                    .then(() => {
                        if (item.orderStatus === '1') { // 待支付
                            let params = {
                                orderId: item.orderId,
                                orderStatus: '1'
                            }
                            this.cancelOrderFun(params);
                        } else {
                            this.$refs.cancelForm.resetValidation();
                            this.cancelFormData = {
                                orderId: item.orderId,
                                orderStatus: item.orderStatus,
                                retreatReason: ''
                            }
                            this.showCancelModal = true;
                        }
                    })
                    .catch(() => { });
            },
            // 确定取消
            handleSure () {
                this.$refs.cancelForm.validate().then(() => {
                    let params = {
                        orderId: this.cancelFormData.orderId,
                        orderStatus: this.cancelFormData.orderStatus,
                        retreatReason: this.cancelFormData.retreatReason
                    }
                    this.cancelOrderFun(params);
                })
            },
            // 取消订单
            cancelOrderFun (params) {
                this.spinLoading = true;
                updateCancelOrder(params).then(res => {
                    this.spinLoading = false;
                    if (res.code === 1000) {
                        this.showCancelModal = false;
                        this.$Notify({ type: 'success', message: '订单取消成功！' });
                        this.onRefresh();
                    }
                }).catch(() => {
                    this.spinLoading = false;
                })
            },
            // 退款
            handleUpdRefund (item) {
                let text = item.afterSalesStatus === '2' ? '修改退款信息' : '退款';
                this.$Dialog
                    .confirm({
                        title: `是否确定${text}？`,
                    })
                    .then(() => {
                        this.$refs.refundFormRef.getOrderData(item);
                        this.showUpdRefundModal = true;
                    })
                    .catch(() => { });
            },
            // 删除订单
            handleDelete (item) {
                this.$Dialog
                    .confirm({
                        title: "是否确定删除该退款信息？",
                    })
                    .then(() => {
                        this.spinLoading = true;
                        delOrderBack(item.orderId).then(res => {
                            this.spinLoading = false;
                            if (res.code === 1000) {
                                this.$Notify({ type: 'success', message: '删除成功！' });
                                this.onRefresh();
                            }
                        }).catch(() => {
                            this.spinLoading = false;
                        })
                    })
                    .catch(() => { });
            },
            // 获取图片信息
            queryFileInfoData (fileCodeArr) {
                this.loading = true;
                queryFileList(fileCodeArr).then(res => {
                    if (res.code === 1000 && res.data) {
                        res.data.forEach(item => {
                            this.fileUrlObj[item.fileCode] = item.url;
                        })
                        this.$forceUpdate();
                        this.loading = false;
                    }
                }).catch(() => {
                    this.loading = false;
                })
            },
            // 标准代码值
            queryDicData () {
                // 餐次
                queryDic('SA_MEALS_TYPE_CODE').then(res => {
                    if (res.code === 1000 && res.data) {
                        this.mealsTypeList = res.data;
                    }
                })
            }
        }
    }
</script>

<style scoped lang='less'>
    .search-row {
        align-items: center;
        .van-icon {
            font-size: 20px;
            color: #fff;
            margin-right: 13px;
        }
    }
    .listCon {
        padding: 1px 0 0;
        /deep/.van-tabs__wrap {
            height: 35px;
            margin-bottom: 5px;
            .van-tabs__line {
                background-color: #2db7f5;
            }
            .van-tab__text {
                font-size: 13px;
            }
        }
        .orderList {
            padding: 4px 8px 0;
            box-sizing: border-box;
            height: calc(100% - 46px);
            overflow: auto;
            .list-item {
                background: #fff;
                padding: 8px;
                margin-bottom: 8px;
                border-radius: 5px;
            }
            .flexRow {
                display: flex;
                justify-content: space-between;
            }
            .head {
                margin-bottom: 8px;
                .left {
                    flex: 1;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    b {
                        margin-right: 5px;
                    }
                    span {
                        font-size: 12px;
                    }
                }
                .right {
                    margin-left: 5px;
                    width: 75px;
                    text-align: right;
                }
            }
            .middle {
                width: 100%;
                padding-right: 60px;
                box-sizing: border-box;
                position: relative;
                & > div {
                    display: flex;
                    width: 100%;
                    overflow-x: auto;
                }
                & > div::-webkit-scrollbar {
                    width: 0 !important;
                    height: 0 !important;
                }
                .tip {
                    font-size: 11px;
                    position: absolute;
                    right: -3px;
                    top: 40%;
                    transform: translateY(-50%);
                    width: 60px;
                    text-align: center;
                }
                dl {
                    margin-right: 10px;
                    dt {
                        width: 70px;
                        height: 70px;
                        position: relative;
                        border-radius: 3px;
                        overflow: hidden;
                        img {
                            width: 100%;
                            height: 100%;
                        }
                        p {
                            position: absolute;
                            bottom: 0;
                            left: 0;
                            right: 0;
                            font-size: 12px;
                            height: 22px;
                            line-height: 22px;
                            background: rgba(0, 0, 0, 0.4);
                            color: #fff;
                            padding: 0 5px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                            box-sizing: border-box;
                            text-align: center;
                        }
                    }
                    dd {
                        display: flex;
                        justify-content: space-between;
                        font-size: 11px;
                        margin-top: 5px;
                        .buyAmount {
                            text-align: right;
                            color: #999;
                        }
                    }
                }
            }
            .orderInfo {
                height: 25px;
                line-height: 25px;
                color: #999;
                span {
                    color: #333;
                }
            }
            .bottom {
                height: 25px;
                line-height: 25px;
                margin-top: 3px;
                a {
                    font-size: 11px;
                    border: 1px solid #ddd;
                    padding: 5px 8px;
                    border-radius: 10px;
                    margin-left: 5px;
                }
            }
            .status {
                color: orange;
                margin: 0 5px 0 10px;
            }
            .status4 {
                color: #20bc12;
            }
            .status5,
            .status6 {
                color: rgb(242, 36, 36);
            }
            .money {
                color: rgb(242, 36, 36);
            }
            .surplusTime {
                display: flex;
                font-size: 13px;
                span {
                    color: rgb(242, 36, 36);
                }
            }
        }
    }
</style>